package com.maizi.utils;

import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: HttpClient
 * @Description: http请求工具类
 * @author 麦子 wheat235@gmail.com
 */
public class HttpClient {

	private static final Logger log = LoggerFactory.getLogger(HttpClient.class);

	private static final String defaultCharset = "UTF-8";

	/**
	 * Get请求获得http响应字符串
	 * 
	 * @param url:请求地址
	 * @param params:请求参数
	 * @return http响应字符串
	 * @throws KeyStoreException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static String doGet(String url, Map<String, String> params) {

		CloseableHttpClient httpClient = null;

		CloseableHttpResponse response = null;
		String result = null;
		try {

			// 创建Httpclient对象
			httpClient = HttpClients.createDefault();

			// 请求的url 如：http://www.baidu.com/s
			URIBuilder uriBuilder = new URIBuilder(url);
			// 定义请求的参数
			if (params != null) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					uriBuilder.setParameter(entry.getKey(), entry.getValue());
				}
			}
			URI uri = uriBuilder.build();
			HttpGet httpGet = new HttpGet(uri);

			httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
			httpGet.setHeader("Accept-Language", "zh-CN");
			httpGet.setHeader("User-Agent",
			        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");

			// httpGet.set
			// 执行请求
			response = httpClient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity(), defaultCharset);
			}
			log.info(result);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			closeClient(response, httpClient);
		}

		return result;
	}

	/***
	 * Post请求获得http响应字符串
	 * 
	 * @param url:请求地址
	 * @param params:请求参数
	 * @return http响应字符串
	 */
	public static String doPost(String url, Map<String, String> params) {

		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (params != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> entry : params.entrySet()) {
					paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), defaultCharset);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeClient(response, httpClient);
		}

		return resultString;
	}

	// 无参数的Get请求
	public static String doGet(String url) {

		return doGet(url, null);
	}

	// 无参数的Post请求
	public static String doPost(String url) {

		return doPost(url, null);
	}

	// 关闭HttpClient
	private static void closeClient(CloseableHttpResponse response, CloseableHttpClient httpclient) {

		try {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
